package task1;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class SinCosSeries implements Callable<Double> {

	private double _start, _end, _step;

	public SinCosSeries(double start, double end, double step) {
		_start = start;
		_end = end;
		_step = step;
	}

	public Double call() throws Exception {
		double result = 0.0;
		for (double i = _start; i <= _end; i += _step) {
			result += Math.sin(i) * Math.cos(i);
		}
		return new Double(result);
	}

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		final int THREAD_COUNT = 4;
		final double N = 1000.0;
		final double STEP = 0.0001;

		double partForThread = (2 * N) / THREAD_COUNT;
		double seriesSum = 0.0;

		ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);

		for(int i = 0; i < THREAD_COUNT; i++) {
			double myStart = partForThread * i - N;
			double myEnd = myStart + partForThread;
			if (i > 0) {
				myStart += STEP;
			}

			Callable<Double> callable = new SinCosSeries(myStart, myEnd, STEP);
            Future<Double> future = executor.submit(callable);
            seriesSum += future.get().doubleValue();
        }

		System.out.println("Result is: " + seriesSum);

		executor.shutdown();
	}
}